<template>
  <i-dialog
    title="选择区域"
    class="region-dialog"
    :visible="visible"
    width="642px"
    :close-on-click-modal="false"
    @close="outerClose"
  >
    <div class="search-wrapper">
      <i-form
        :items="formItems"
        :inline="true"
        :model="form"
        :rules="rules"
        ref="form"
        label-width="0px"
        class="search-form"
      >
        <template slot="cascader">
          <el-form-item prop="filterCascader">
            <HycAddressCascader
              ref="area"
              v-model="area"
              :clearable="true"
              :showLabel="true"
            />
          </el-form-item>
        </template>
        <template slot="nameInput">
          <el-form-item prop="filterInput">
            <el-autocomplete
              ref="autocomplete"
              v-scrollLoad="selectLoadMore"
              v-loading="scrollLoading"
              v-model="form.filterInput"
              :trigger-on-focus="false"
              :fetch-suggestions="querySearch"
              placeholder="请输入区域关键词"
              @select="handleKeyWordsSelect"
              @clear="handleKeyWordsClear"
              clearable
            >
              <template slot-scope="{ item }">
                <ellipsisTooltip :text="item.value" />
              </template>
            </el-autocomplete>
          </el-form-item>
        </template>
      </i-form>
      <div class="btn-wrapper">
        <el-button type="primary" @click="handleSearch" icon="el-icon-search"
          >查询</el-button
        >
      </div>
    </div>
    <div class="area-tree">
      <el-tree
        :data="treeData"
        :show-checkbox="showCheckbox"
        :props="defaultProps"
        ref="tree"
        :node-key="code"
        :default-expand-all="false"
        :lazy="lazy"
        :load="loadNode"
      >
      </el-tree>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="outerClose">取 消</el-button>
      <el-button type="primary" @click="submit">保存</el-button>
    </span>
  </i-dialog>
</template>
<script>
// import _ from 'lodash'
// import formValidate from '@/utils/validate'
import { getCascaderArea, getRegionName } from '@/api/common'
import HycAddressCascader from '@/components/hycAddressCascader'
import EllipsisTooltip from './EllipsisTooltip.vue'
export default {
  name: 'SearchTreeDialog',
  components: {
    HycAddressCascader,
    EllipsisTooltip,
  },
  props: {
    checkedKeys: Array,
    treeInfo: Array,
    visible: {
      type: Boolean,
      required: true,
    },
    code: {
      type: String,
      default: 'code',
    },
    level: {
      type: Number,
      default: 5,
    },
    lazy: {
      type: Boolean,
      default: true,
    },
    showCheckbox: {
      type: Boolean,
      default: true,
    },
    clearable: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      treeData: this.treeInfo,
      area: null,
      radio: '', //  这一行
      regionOptions: [],
      currentPage: 1,
      pageTotal: 0,
      scrollLoading: false,
      defaultProps: {
        label: 'name',
        isLeaf: 'leaf',
      },
      form: {
        filterInput: '',
      },
      filterCode: {},
      formItems: [
        {
          slot: 'cascader',
          span: 12,
        },
        {
          slot: 'nameInput',
          span: 12,
        },
      ],
      rules: {},
      checkedRegions: [],
    }
  },
  watch: {
    checkedKeys(val) {
      this.$refs.tree.setCheckedKeys(val)
    },
    area: {
      handler: function (val) {
        this.form.filterInput = ''
        if (val && val.length) {
          let lastObj = val[val.length - 1]
          this.filterKeyWordsObj = {
            code: lastObj.split(',')[0],
            name: lastObj.split(',')[1],
            level: lastObj.split(',')[2],
          }
        } else {
          this.filterKeyWordsObj = null
        }
      },
      deep: true,
    },
  },
  methods: {
    outerClose() {
      this.form = {}
      this.$emit('update:visible', false)
    },
    //下拉框获取焦点
    Focus() {
      if (typeof this.selectFocus === 'function') {
        this.selectFocus()
      }
    },
    // //树形节点选择
    checkchange() {
      // this.sure()
    },
    async querySearch(val, cb) {
      if (!val) return
      this.currentPage = 1
      this.scrollLoading = true
      try {
        let params = Object.assign(
          {},
          { currentPage: this.currentPage, name: val },
          this.area &&
            this.area.length && {
              code: this.area[this.area.length - 1],
            }
        )
        let { list, totalAmount } = await getRegionName(params)
        if (list) {
          let result = list.map((item) => {
            return {
              value: item.namePath,
              code: item.code,
              name: item.name,
            }
          })
          cb(result)
        } else {
          cb([])
        }
        this.pageTotal = totalAmount || 0
      } catch (e) {
        // console.log(e)
      } finally {
        this.scrollLoading = false
      }
    },
    // 加载更多
    async selectLoadMore() {
      if (
        Number(this.pageTotal) <=
        this.$refs['autocomplete'].$data.suggestions.length
      ) {
        return
      }
      this.currentPage = this.currentPage + 1
      this.scrollLoading = true
      try {
        let params = Object.assign(
          {},
          { currentPage: this.currentPage, name: this.form.filterInput },
          this.area &&
            this.area.length && {
              code: this.area[this.area.length - 1],
            }
        )
        let { list, totalAmount } = await getRegionName(params)
        if (list) {
          let result = list.map((item) => {
            return {
              value: item.namePath,
              code: item.value,
              name: item.name,
              level: item.level,
            }
          })
          this.$refs['autocomplete'].$data.suggestions = this.$refs[
            'autocomplete'
          ].$data.suggestions.concat(result)
        }
        this.pageTotal = totalAmount || 0
      } catch (e) {
        // console.log(e)
      } finally {
        this.scrollLoading = false
      }
    },
    handleKeyWordsSelect(val) {
      this.form.filterInput = val.name
      this.filterKeyWordsObj = val
    },
    handleKeyWordsClear() {
      this.filterKeyWordsObj = null
    },
    async handleSearch() {
      if (this.filterKeyWordsObj) {
        let data = [JSON.parse(JSON.stringify(this.filterKeyWordsObj))]
        data.map((item) => {
          return {
            code: item.code,
            name: item.name,
            level: item.level,
          }
        })
        this.treeData = data
      } else {
        this.treeData = await getCascaderArea({ code: 0 })
      }
    },
    //清空
    clear() {
      this.form = []
      this.filterText = ''
      this.$refs.eltree.setCheckedKeys([])
    },
    //全选
    all() {
      if (this.isAll == false) {
        this.$refs.eltree.setCheckedNodes(this.childData)
        this.isAll = true
      } else {
        this.$refs.eltree.setCheckedKeys([])
        this.isAll = false
      }
    },
    async loadNode(node, resolve) {
      // if (this.lazyFn && typeof this.lazyFn === 'function') {
      //   return this.lazyFn(node, resolve)
      // }

      if (node.level > this.level) return resolve([])
      const params = node.level === 0 ? { code: 0 } : { code: node.data.code }
      let data = await getCascaderArea(params)
      data.forEach((item) => {
        item.leaf = item.level >= this.level + 1
      })
      return resolve(data)
    },
    getSimpleCheckedNodeIds(originData) {
      // 定义数组
      const checkedNodes = []
      // 判断是否为全选，若为全选状态返回被全选的节点，不为全选状态正常返回被选中的节点
      const isAllChecked = function (node) {
        const childNodes = node.root ? node.root.childNodes : node.childNodes
        childNodes.forEach((child) => {
          if (child.checked) {
            checkedNodes.push(child.data)
          }
          if (child.indeterminate) {
            isAllChecked(child)
          }
        })
      }
      isAllChecked(originData)
      return checkedNodes
    },
    submit() {
      let list = this.$refs.tree.getCheckedNodes()
      console.log(this.getSimpleCheckedNodeIds(this.$refs.tree.store))
      this.$emit('listenCheckedInfoEvent', list)
      this.outerClose()
    },
  },
}
</script>
<style lang="scss" scoped>
.region-dialog {
  .area-tree {
    height: 450px;
    overflow: auto;
  }
}
.search-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .search-form {
    display: flex;
    &::v-deep .address-cascader {
      margin-right: 10px;
    }
  }
}
</style>
